import React, { useEffect } from 'react';
import { DatePicker, Select, Button } from 'antd';
import { useDebounceFn } from 'ahooks';
import { connect } from 'umi';

import { TRMessage } from '#/components';
import { UploadOutlined } from '#/utils/antdIcons';
import { export_json_to_excel } from '@/utils/fileExport.js';
import styles from './index.less';

const { RangePicker } = DatePicker;
const { Option } = Select;

export const SequenceOperate = (props) => {
  const [marketId, setMarketId] = React.useState(props.marketId);

  // 初始化页面数据
  useEffect(() => props.handlePageLoadSequenceEffect(), []);

  // 默认查询页面
  useEffect(() => {
    if (!props.provinceIdMarket) return;
    query();
  }, []);
  // 查询
  const query = () => {
    props.fetchSequenceAccountedEffect();
  };
  // 重置
  const _reset = useDebounceFn(
    async () => {
      setMarketId(props.marketId);
      props.setProvinceIdMarket(props.marketList[0].provinceId);
      props.setMarketIdMarket(props.marketList[0].marketId);
      props.handlePageLoadSequenceEffect();
      query();
    },
    { wait: 500 },
  );

  // 导出
  const exportExcel = () => {
    if (
      !props.buttonPermissions.filter((item) => item.menuCode === 'SequenceAccountedExport').length
    ) {
      return TRMessage.info('请联系管理员获取相关权限');
    }

    let params = {
      multiHeader: [
        ['时点', '汇总', '', '', '', '月中长期', '', '', '旬中长期', '', '', '日中长期', '', ''],
      ],
      header: null,
      data: null,
      filename: null,

      merges: ['A1:A2', 'B1:E1', 'F1:H1', 'I1:K1', 'L1:N1'],
    };
    params.header = [
      '时点',
      '回收参考价',
      '总成交电量',
      '总成交电费',
      '加权均价',
      '总成交电量',
      '总成交电费',
      '加权均价',
      '总成交电量',
      '总成交电费',
      '加权均价',
      '总成交电量',
      '总成交电费',
      '加权均价',
    ];
    let data = [];
    props.sequenceProportionTableData.map((t) => {
      data.push([
        t.timeOrder,
        t.sumRecoveryReferencePrice,
        t.sumTotalQuantity,
        t.sumTotalElectricity,
        t.sumElectricityPrice,
        t.monthTotalQuantity,
        t.monthTotalElectricity,
        t.monthElectricityPrice,
        t.periodTotalQuantity,
        t.periodTotalElectricity,
        t.periodElectricityPrice,
        t.dayTotalQuantity,
        t.dayTotalElectricity,
        t.dayElectricityPrice,
      ]);
    });
    params.data = data;
    params.filename = '市场成交行情分析';
    export_json_to_excel(params);
  };

  return (
    <div className={styles.SequenceOperate}>
      <div className={styles.condition}>
        <Select
          showSearch
          filterOption={(input, option) => {
            return (option?.label).toLowerCase().includes(input.toLowerCase());
          }}
          className={styles.provinceSelect}
          value={props.marketIdMarket}
          onChange={(e, { provinceId }) => {
            props.setMarketIdMarket(e);
            props.setProvinceIdMarket(provinceId);
          }}
          options={props.marketList}
        />
        <RangePicker
          className={styles.dataPicker}
          allowClear={false}
          value={props.sequenceProportionDate}
          format="YYYYMMDD"
          onChange={props.setSequenceProportionDate}
          separator="-"
        />
        <Button className={styles.queryBtn} type="primary" onClick={query}>
          查询
        </Button>
        <Button className={styles.queryBtn} onClick={_reset.run} type="ghost">
          重置
        </Button>
      </div>
      {props.sequenceProportionChartDate ? (
        <Button style={{ padding: 0 }} type="link" icon={<UploadOutlined />} onClick={exportExcel}>
          导出
        </Button>
      ) : null}
    </div>
  );
};

const mapStateToProps = ({ mediumAndLongTermMarket, global }) => ({
  buttonPermissions: global.configure.buttonPermissions,
  provinceList: mediumAndLongTermMarket.provinceList,
  provinceIdMarket: mediumAndLongTermMarket.provinceIdMarket,
  sequenceProportionDate: mediumAndLongTermMarket.sequenceProportionDate,
  sequenceProportionTableData: mediumAndLongTermMarket.sequenceProportionTableData,
  sequenceProportionChartDate: mediumAndLongTermMarket.sequenceProportionChartDate,
  marketList: mediumAndLongTermMarket.marketList,
  marketId: mediumAndLongTermMarket.marketId,
  marketIdMarket: mediumAndLongTermMarket.marketIdMarket,
});

const mapDispatchToProps = (dispatch) => ({
  fetchSequenceAccountedEffect: () =>
    dispatch({
      type: 'mediumAndLongTermMarket/fetchSequenceAccountedEffect',
    }),
  setSequenceProportionDate: (payload) =>
    dispatch({
      type: 'mediumAndLongTermMarket/setSequenceProportionDate',
      payload,
    }),
  setSequenceProportionChartData: (payload) =>
    dispatch({
      type: 'mediumAndLongTermMarket/setSequenceProportionChartData',
      payload,
    }),
  setSequenceProportionTableData: (payload) =>
    dispatch({
      type: 'mediumAndLongTermMarket/setSequenceProportionTableData',
      payload,
    }),
  handlePageLoadSequenceEffect: () =>
    dispatch({
      type: 'mediumAndLongTermMarket/handlePageLoadSequenceEffect',
    }),
  setProvinceIdMarket: (payload) =>
    dispatch({
      type: 'mediumAndLongTermMarket/setProvinceIdMarket',
      payload,
    }),
  setMarketIdMarket: (payload) =>
    dispatch({
      type: 'mediumAndLongTermMarket/setMarketIdMarket',
      payload,
    }),
});

export default connect(mapStateToProps, mapDispatchToProps)(SequenceOperate);
